<template>
  <div class="progress-plan-totality-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="search-container">
        <div class="search-item">
          <div class="item plan-item">
            <el-select v-model="scheduleType" placeholder="请选择">
              <el-option value="0" label="总计划"></el-option>
              <el-option value="1" label="月计划"></el-option>
            </el-select>
          </div>
          <div class="item">
            <span class="label">关键字：</span>
            <el-input
              placeholder="请输入"
              v-model="scheduleName"
              clearable
              @keydown.native.enter="handleSearch">
            </el-input>
          </div>
          <div class="item">
            <span class="lable">日期：</span>
            <el-date-picker
              v-show="hasMonth"
              v-model="scheduleMonth"
              format="yyyy-MM"
              value-format="yyyy-MM"
              type="month"
              placeholder="选择月">
            </el-date-picker>
            <el-date-picker
              v-show="!hasMonth"
              v-model="searchDate"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
              :default-time="['00:00:00', '23:59:59']"
              @keydown.native.enter="handleSearch">
            </el-date-picker>
          </div>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>
          </el-button>
          <el-button type="primary" @click="handleRefresh">
            <i class="el-icon-refresh"></i>
          </el-button>
          <el-checkbox
            true-label="1"
            false-label="0"
            :value="setMilepostFlag"
            @change="handleChange">
            仅显示里程碑节点
          </el-checkbox>
        </div>
        <div class="search-item">
          <el-button v-if="hasTabAdd" type="primary" @click="handleAdd">
            新建
          </el-button>
          <el-dropdown>
            <el-button type="primary">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown" class="progress-plan-totality-dropdown">
              <el-dropdown-item v-if="hasTabDownload">
                <el-button type="primary" @click="getUploadTemplate">
                  模版下载
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item v-if="hasTabImport">
                <el-button type="primary" :loading="importLoading" class="upload-file">
                  <input class="file" ref="file" type="file" @change="handleImport" />
                  导 入
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item v-if="hasTabExport">
                <el-button type="primary" @click="handleExport">导 出</el-button>
              </el-dropdown-item>
              <el-dropdown-item v-if="hasTabSet">
                <el-button type="primary" @click="handleSetMilestone">设置里程碑</el-button>
              </el-dropdown-item>
              <template v-if="checkId">
                <el-dropdown-item v-show="hasTabDetail && !hasMonth">
                  <el-button type="primary" @click="handleHistory">历史记录</el-button>
                </el-dropdown-item>
<!--                <el-dropdown-item>-->
<!--                  <el-button type="primary" @click="handleFeedback">反馈</el-button>-->
<!--                </el-dropdown-item>-->
                <el-dropdown-item v-if="hasTabEdit">
                  <el-button type="primary" @click="handleEdit">编辑</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasTabDelete">
                  <el-button type="primary" @click="handleDelete">删除</el-button>
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-table
        class="table-container"
        :data="tableData"
        v-loading="tableLoading"
        element-loading-custom-class="custom-load"
        row-key="id">
        <el-table-column label="选择" prop="id" width="80" align="center" fixed="left" >
          <template slot-scope="scope">
            <el-checkbox :value="scope.row.checked" @change="(e) => handleCheck(e, scope.row)"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" type="index" width="80"></el-table-column>
        <el-table-column label="任务名称" show-overflow-tooltip prop="scheduleName" width="300"></el-table-column>
        <el-table-column label="工期" prop="projectTime" width="120"></el-table-column>
        <el-table-column label="计划开始" prop="planStartTime" width="120">
<!--          <template slot-scope="scope">-->
<!--            <div class="flag">-->
<!--              <template v-if="scope.row.setStartFlag === '1'">-->
<!--                <i title="已设置里程碑" class="iconfont iconlichengbei"></i>-->
<!--                <span>{{ scope.row.planStartTime }}</span>-->
<!--              </template>-->
<!--              <span v-else class="plan" @click="handleSetPlan(scope.row, '1')">-->
<!--                {{ scope.row.planStartTime }}-->
<!--              </span>-->
<!--            </div>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column label="计划完成" prop="planEndTime" width="120">
<!--          <template slot-scope="scope">-->
<!--            <div class="flag">-->
<!--              <template v-if="scope.row.setEndFlag === '1'">-->
<!--                <i title="已设置里程碑" class="iconfont iconlichengbei"></i>-->
<!--                <span class="plan">-->
<!--                  {{ scope.row.planEndTime }}-->
<!--                </span>-->
<!--              </template>-->
<!--              <span v-else class="plan" @click="handleSetPlan(scope.row, '2')">-->
<!--                {{ scope.row.planEndTime }}-->
<!--              </span>-->
<!--            </div>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column label="实际开始" prop="actualStartTime" width="120"></el-table-column>
        <el-table-column label="实际完成" prop="actualEndTime" width="120"></el-table-column>
        <el-table-column label="偏差天数" prop="deviationDay" width="120"></el-table-column>
        <el-table-column label="前置任务" show-overflow-tooltip prop="preTask" width="150"></el-table-column>
        <el-table-column class-name="graph-column" :min-width="widthOptions.width" label="横道图" :render-header="renderHeader">
          <template slot-scope="scope">
            <ul class="graph plan" :title="`计划时间: ${scope.row.planStartTime} - ${scope.row.planEndTime}`">
              <li
                :class="[
                  'text',
                  item >= graphPlanWidth(scope.row).startNum && item <= graphPlanWidth(scope.row).endNum ? 'active' : '',
                  item === graphPlanWidth(scope.row).startNum ? 'start' : '',
                  item === graphPlanWidth(scope.row).endNum ? 'end' : '',
                ]"
                v-for="(item, i) in (widthOptions.num * 12)"
                :key="i">
              </li>
            </ul>
            <ul
              v-if="scope.row.actualStartTime && scope.row.actualEndTime"
              class="graph"
              :title="`实际时间: ${scope.row.actualStartTime} - ${scope.row.actualEndTime}`">
              <li
                :class="[
                  'text',
                  item >= graphWidth(scope.row).startNum && item <= graphWidth(scope.row).endNum ? 'active' : '',
                  item === graphWidth(scope.row).startNum ? 'start' : '',
                  item === graphWidth(scope.row).endNum ? 'end' : '',
                ]"
                v-for="(item, i) in (widthOptions.num * 12)"
                :key="i">
              </li>
            </ul>
          </template>
        </el-table-column>
<!--        <el-table-column fixed="right" label="操作" width="200">-->
<!--          <template slot-scope="scope">-->
<!--            <span class="btn" @click="handleHistory(scope.row)">历史记录</span>-->
<!--            <span class="btn" @click="handleEdit(scope.row)">编辑</span>-->
<!--            <span class="btn" @click="handleDelete(scope.row)">删除</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <div class="empty-content" slot="empty">
          <i class="iconfont iconwushuju"></i>
          <p>暂无数据</p>
        </div>
      </el-table>
      <el-pagination
        v-if="total > 10"
        :page-size="pageSize"
        :current-page="pageNo"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </main>
    <add-progress
      :visible="addVisible"
      :loading="addLoading"
      :formData="currentData"
      :addType="addType"
      :scheduleType="scheduleType"
      @submit="handleSetProgress"
      @cancel="addVisible = false">
    </add-progress>
    <set-progress-plan
      :visible="planVisible"
      :loading="planLoading"
      :formData="planData"
      :type="planType"
      @submit="handleSetProgressPlan"
      @cancel="planVisible = false">
    </set-progress-plan>
    <set-milestone
      :visible="milestoneVisible"
      @change="getTableData"
      @cancel="milestoneVisible = false">
    </set-milestone>
    <schedule-history
      :visible="historyVisible"
      :id="checkId"
      @cancel="historyVisible = false">
    </schedule-history>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import addProgress from '@/components/project/progress/addProgress';
import setProgressPlan from '@/components/project/progress/setProgressPlan';
import setMilestone from '@/components/project/progress/setMilestone';
import scheduleHistory from '@/components/project/progress/scheduleHistory';
import tableHeader from '@/components/project/progress/tableHeader';

export default {
  data() {
    return {
      breadcrumbData: [
        { name: '进度管理' },
        { name: '总体进度' }
      ],
      // tabs选中值
      scheduleType: '0',
      // 期间计划查询
      scheduleMonth: this.$moment().format('yyyy-MM'),
      // 关键字（进度名称）
      scheduleName: '',
      // 搜索时间
      searchDate: [],
      // 是否设置里程碑
      setMilepostFlag: '',
      importLoading: false,
      hasSearch: false,
      tableData: [],
      tableLoading: false,
      total: 0,
      pageSize: 10,
      pageNo: 1,
      addVisible: false,
      addLoading: false,
      addType: 'add',
      currentData: {},
      planVisible: false,
      planLoading: false,
      planData: {},
      planType: '',
      milestoneVisible: false,
      historyVisible: false,
      checkId: ''
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    // 是否为月计划
    hasMonth() {
      return this.scheduleType === '1';
    },
    startDate() {
      return this.tableData.reduce((pre, next) => {
        const { planStartTime, actualStartTime } = next;
        const planStartTimeStr = planStartTime
          ? new Date(planStartTime).getTime()
          : '0';
        const actualStartTimeStr = actualStartTime
          ? new Date(actualStartTime).getTime()
          : '0';
        const currentDate = planStartTimeStr > actualStartTimeStr
          ? actualStartTime || planStartTime
          : planStartTime || actualStartTimeStr;
        if (pre === '0') return currentDate;
        const preTime = new Date(pre).getTime();
        const currentTime = new Date(currentDate).getTime();
        return currentTime > preTime ? pre : currentDate;
      }, '0');
    },
    endDate() {
      return this.tableData.reduce((pre, next) => {
        const { planEndTime, actualEndTime } = next;
        const planEndTimeStr = planEndTime
          ? new Date(planEndTime).getTime()
          : '0';
        const actualEndTimeStr = actualEndTime
          ? new Date(actualEndTime).getTime()
          : '0';
        const currentDate = planEndTimeStr > actualEndTimeStr
          ? planEndTime || actualEndTime
          : actualEndTime || planEndTime;
        if (pre === '0') return currentDate;
        const preTime = pre ? new Date(pre).getTime() : pre;
        const currentTime = new Date(currentDate).getTime();
        return currentTime > preTime ? currentDate : pre;
      }, '0');
    },
    widthOptions() {
      const startYear = new Date(this.startDate || new Date()).getFullYear();
      const endYear = new Date(this.endDate || new Date()).getFullYear();
      const num = Math.abs(endYear - startYear) + 1;
      return {
        width: this.$setRem(num * 372, false),
        num
      };
    },
    graphPlanWidth() {
      return (data) => {
        const { planStartTime, planEndTime } = data;
        if (!planStartTime) return {};
        const [planYear] = this.startDate.split('-');
        const [startYear, startMonth] = planStartTime.split('-');
        const [endYear, endMonth] = planEndTime.split('-');
        const leftNum = (startYear - planYear) * 12 + Number(startMonth);
        const widthNum = (endYear - startYear) * 12 + endMonth - startMonth;
        return {
          startNum: leftNum,
          endNum: (endYear - planYear) * 12 + Number(endMonth),
          left: this.$setRem(leftNum * 30, false) + 'px',
          width: this.$setRem(widthNum * 30, false) + 'px'
        };
      };
    },
    graphWidth() {
      return (data) => {
        const { actualStartTime, actualEndTime } = data;
        if (!actualStartTime || !actualEndTime) return {};
        const [planYear] = this.startDate.split('-');
        const [startYear, startMonth] = actualStartTime.split('-');
        const [endYear, endMonth] = actualEndTime.split('-');
        const leftNum = (startYear - planYear) * 12 + Number(startMonth);
        const widthNum = (endYear - startYear) * 12 + endMonth - startMonth;
        return {
          startNum: leftNum,
          endNum: (endYear - planYear) * 12 + Number(endMonth),
          left: this.$setRem(leftNum * 30, false) + 'px',
          width: this.$setRem(widthNum * 30, false) + 'px'
        };
      };
    }
  },
  watch: {
    scheduleType: {
      immediate: true,
      handler(val) {
        if (!val) return;
        this.getTableData();
      }
    }
  },
  components: {
    Breadcrumb,
    addProgress,
    setMilestone,
    scheduleHistory,
    setProgressPlan
  },
  methods: {
    // 获取总体进度
    async getTableData(options = {}) {
      const params = {
        pageSize: this.pageSize,
        pageNum: this.pageNo,
        projectId: this.projectId,
        scheduleType: this.scheduleType,
        scheduleMonth: this.scheduleMonth,
        ...options
      };
      if (this.setMilepostFlag === '1') {
        params.setMilepostFlag = this.setMilepostFlag;
      }
      if (this.hasSearch) {
        if (this.searchDate && this.searchDate.length) {
          params.planStartTime = this.searchDate[0];
          params.planEndTime = this.searchDate[1];
        }
        params.scheduleName = this.scheduleName;
      }
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.getProgressList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        this.tableData = list.map(item => ({
          ...item,
          checked: false
        }));
        this.total = data.total || 0;
      }
    },
    renderHeader(h, data) {
      return h(tableHeader, {
        props: {
          startDate: this.startDate,
          endDate: this.endDate
        }
      });
    },
    /**
     * 搜索
     */
    handleSearch() {
      this.clear();
      this.hasSearch = (!!this.searchDate && this.searchDate.length) || this.scheduleName;
      this.getTableData();
    },
    // 重置
    handleRefresh() {
      this.clear();
      this.hasSearch = false;
      this.searchDate = [];
      this.getTableData();
    },
    // 选中某项
    handleCheck(checked, row) {
      this.tableData.forEach(item => {
        if (item.id === row.id) {
          item.checked = checked;
          this.checkId = checked ? row.id : '';
          this.currentData = checked ? { ...row } : {};
          return;
        }
        item.checked = false;
      });
    },
    // 是否设置里程碑
    handleChange(val) {
      this.setMilepostFlag = val;
      this.getTableData();
    },
    handleAdd() {
      this.currentData = {};
      this.addType = 'add';
      this.addVisible = true;
    },
    // 模板下载
    async getUploadTemplate() {
      const { success, message } = await this.$Model.getUploadTemplate({
        projectId: this.projectId
      });
      if (success && message) {
        window.open(this.$configs.upload + message);
      }
    },
    // 导入
    async handleImport(e) {
      const file = e.target.files && e.target.files[0];
      if (!file || this.importLoading) return;
      const fm = new FormData();
      fm.append('file', file);
      this.importLoading = true;
      const { success } = await this.$Model.uploadExcel({
        projectId: this.projectId,
        file: fm
      });
      this.$refs.file.value = '';
      this.importLoading = false;
      if (success) {
        this.$message.success('导入成功');
        this.getTableData();
      }
    },
    // 导出当前页面数据
    handleExport() {
      const href = `${this.$configs.baseURL}/bus/schedule/master/downLoadXlsByJxl`;
      const params = {
        projectId: this.projectId,
        pageFlag: false,
        planStartTime: this.searchDate[0] || '',
        planEndTime: this.searchDate[1] || '',
        scheduleName: this.scheduleName,
        scheduleMonth: this.scheduleMonth,
        scheduleType: this.scheduleType,
        setMilepostFlag: this.setMilepostFlag
      };
      let urlStr = '';
      Object.keys(params).forEach((key, index) => {
        const value = params[key] === undefined ? '' : params[key];
        urlStr += `${index === 0 ? '?' : '&'}${key}=${value}`;
      });
      window.open(href + urlStr);
    },
    // 设置里程碑
    handleSetMilestone() {
      this.milestoneVisible = true;
    },
    // 清除参数
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
      this.tableLoading = false;
      this.tableData = [];
      this.checkId = '';
      this.currentData = {};
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getTableData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getTableData();
    },
    // 查看历史记录
    handleHistory() {
      this.historyVisible = true;
    },
    // 编辑
    handleEdit() {
      this.addType = 'edit';
      this.currentData = {
        ...this.currentData
      };
      this.addVisible = true;
    },
    // 反馈
    handleFeedback() {
      this.addType = 'feedback';
      this.currentData = {
        ...this.currentData
      };
      this.addVisible = true;
    },
    // 删除
    handleDelete() {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.deleteProgress({
          ids: this.checkId
        });
        if (success) {
          this.$message.success('删除成功');
          this.clear();
          this.getTableData();
        }
      });
    },
    // 保存进度设置
    async handleSetProgress(data) {
      const {
        planTime = [],
        actualTime = [],
        actualStartTime,
        actualEndTime,
        ...options
      } = data;
      const params = {
        ...options,
        projectId: this.projectId
      };
      if (this.addType === 'add') {
        delete params.id;
        params.scheduleType = this.scheduleType;
        params.planStartTime = planTime[0] || '';
        params.planEndTime = planTime[1] || '';
      } else if (this.addType === 'edit') {
        if (this.scheduleType === '1') { // 月计划
          params.actualStartTime = actualTime[0] || '';
          params.actualEndTime = actualTime[1] || '';
        }
      } else {
        params.actualStartTime = actualStartTime || '';
        params.actualEndTime = actualEndTime || '';
      }
      this.addLoading = true;
      const { success } = this.addType === 'add'
        ? await this.$Model.addProgress(params)
        : this.addType === 'edit'
          ? await this.$Model.updateProgress(params)
          : await this.$Model.progressFeedback(params);
      this.addLoading = false;
      if (success) {
        this.$message.success('设置成功');
        this.getTableData();
        this.addVisible = false;
      }
    },
    handleSetPlan(row, type) {
      this.planType = type;
      this.planData = {
        ...row
      };
      this.planVisible = true;
    },
    // 设置计划时间里程碑
    async handleSetProgressPlan(data) {
      this.planLoading = true;
      const { success } = await this.$Model.scheduleMilepostSet({
        ...data,
        projectId: this.projectId,
        scheduleId: this.planData.id,
        // 设置时间标志；1：开始时间；2：结束时间
        setTimeType: this.planType
      });
      this.planLoading = false;
      if (success) {
        this.$message.success('设置成功');
        this.getTableData();
        this.planVisible = false;
      }
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';

  .progress-plan-totality-page {
    width: 100%;
    height: 100%;
    background-color: $mainBg;
    overflow: hidden;
    main {
      width: 100%;
      height: calc(100% - 50px);
      padding: 20px;
      .search-container {
        width: 100%;
        height: 80px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .search-item {
          height: 100%;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-right: 20px;
            &.plan-item {
              width: 140px;
            }
            .label {
              width: 120px;
            }
          }
          /deep/ .el-checkbox {
            margin-left: 20px;
            &.is-checked {
              .el-checkbox__label {
                color: $successBtn;
              }
            }
            .el-checkbox__label {
              color: #fff;
            }
          }
          .el-dropdown {
            margin-left: 10px;
          }
        }
      }
      .table-container {
        height: calc(100% - 120px);
        .btn {
          padding: 0 5px;
          cursor: pointer;
          color: $mainColor;
        }
        /deep/ .el-table__body-wrapper {
          height: calc(100% - 78px);
          padding-bottom: 46px;
          overflow: auto;
          .plan {
            cursor: pointer;
            padding: 4px 0;
            color: $mainColor;
          }
          .flag {
            position: relative;
            padding-left: 20px;
            .iconlichengbei {
              color: $successBtn;
              cursor: pointer;
              font-size: 12px;
              position: absolute;
              left: 0;
            }
          }
          .graph-column {
            width: 100%;
            height: 100%;
            .cell {
              width: 100%;
              height: 20px;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              .graph {
                width: 100%;
                height: 8px;
                display: flex;
                align-items: center;
                cursor: pointer;
                .text {
                  width: 31px;
                  height: 8px;
                  display: inline-block;
                  background: transparent;
                  transition: background .2s;
                  float: left;
                  &.active {
                    background: green;
                    &.start {
                      border-radius: 20px 0 0 20px;
                    }
                    &.end {
                      border-radius: 0 20px 20px 0;
                    }
                    &.start.end {
                      border-radius: 20px;
                    }
                  }
                }
                &.plan {
                  .text {
                    &.active {
                      background: #8381FF;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  .progress-plan-totality-dropdown {
    .el-dropdown-menu__item {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10px;
      .el-button {
        width: 120px;
      }
    }
    .upload-file {
      position: relative;
      cursor: pointer;
      .file {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        opacity: 0;
        cursor: pointer;
      }
    }
  }
</style>
